package cn.dnui_wwt524.dnuifood_16110100524.fragment;


import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView;
import android.widget.SimpleAdapter;


import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import cn.dnui_wwt524.dnuifood_16110100524.R;
import cn.dnui_wwt524.dnuifood_16110100524.controller.SearchInfoActivity;
import cn.dnui_wwt524.dnuifood_16110100524.db.RecordDBOperation;
import cn.dnui_wwt524.dnuifood_16110100524.db.RecordSQLiteOpenHelper;


public class SearchFragment extends Fragment {


    public RecordDBOperation recordDB;
    public RecordSQLiteOpenHelper helper;
    private TextView tv_clear, tv_tip;
    private EditText et_search;
    private Button btn_ok;
    private HistoryListView listView;
    private View view;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        helper=new RecordSQLiteOpenHelper(getActivity());
        recordDB=new RecordDBOperation(helper);
        view=inflater.inflate(R.layout.fragment_search,container,false);
        initViews();
        initEvent();
        return view;
    }

    void initViews() {
        btn_ok = view.findViewById(R.id.btn_ok);
        tv_clear = view.findViewById(R.id.tv_clear);
        et_search = view.findViewById(R.id.et_search);
        listView = view.findViewById(R.id.listView);
        tv_tip = view.findViewById(R.id.tv_tip);
        btn_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                recordDB.insertData(et_search.getText().toString().trim());
                showDetailInfo(et_search.getText().toString().trim());
            }
        });
    }

    public void initEvent() {
        tv_clear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                recordDB.deleteData();
                showData("");
                Toast.makeText(getActivity(),"历史记录已清空",Toast.LENGTH_SHORT).show();
            }
        });

        et_search.setOnKeyListener(new View.OnKeyListener() {
            //输入完后按键盘上的搜索键
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {

                    ((InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                    boolean hasData = recordDB.hasData(et_search.getText().toString().trim());
                    if (!hasData) {
                        recordDB.insertData(et_search.getText().toString().trim());
                        showData("");
                    }
                    showDetailInfo(et_search.getText().toString().trim());
                }
                return false;
            }
        });

        et_search.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                btn_ok.setVisibility(View.VISIBLE);
                if (s.toString().trim().length() == 0) {
                    tv_tip.setText("搜索历史");
                }
                else{
                    tv_tip.setText("搜索结果");
                }
                String tempName = et_search.getText().toString();
                showData(tempName);
            }
        });

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                TextView textView = view.findViewById(R.id.text1);
                String name = textView.getText().toString();
                et_search.setText(name);
                showDetailInfo(name);
            }
        });
    }

    private void showData(String tempName) {
        List list = recordDB.queryData(tempName);
        Set set = new HashSet();
        List newList = new ArrayList();
        for (Iterator iter = list.iterator(); iter.hasNext();) {
            Object element = iter.next();
            if (set.add(element))
                newList.add(element);
        }
        list.clear();
        list.addAll(newList);
        SimpleAdapter adapter = new SimpleAdapter(getActivity(), list, R.layout.simple_list_item, new String[]{"name"}, new int[]{R.id.text1});
        listView.setAdapter(adapter);
        adapter.notifyDataSetChanged();
    }

    void showDetailInfo(String name) {
        Intent intent = new Intent(getActivity(), SearchInfoActivity.class);
        intent.putExtra("search", name);
        startActivity(intent);
    }




}
